package com.syy.compare.core;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

@Service
public class SpringInvoke implements ApplicationContextAware {
    private ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public Object springInvoke(Class clazz, String methodName, Object[] args) throws Exception {
        // 获取Spring容器中的bean
        Object bean = context.getBean(clazz);

        // 获取方法对象
        Method method = null;
        if (null != args && args.length > 0) {
            Class[] argsClass = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                argsClass[i] = args[i].getClass();
            }
            method = clazz.getMethod(methodName, argsClass);
        } else {
            method = clazz.getMethod(methodName);
        }
        return method.invoke(bean, args);
    }
}
